package com.budwk.app.util.poiUtils;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.budwk.app.sqfw.dto.FireHiddenOfficeWordDTO;
import com.budwk.app.sqfw.enums.WeiQingMenPdfType;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.generateWordDocument;

/**
 * @author yangweimin
 * @since 2023/10/9
 *
 * <p>
 * 威清门街道消防安全文档生成工具类
 * </p>
 */
public class WeiQingMenStreetWordTemplate {

    private static final String UNIT_NAME = "威清门街道直属";

    /**
     * 下载word模板
     *
     * @return
     */
    public static String createWordTemplate(FireHiddenOfficeWordDTO formSummary) {
        int index = formSummary.getIndex();
        String fileName = WeiQingMenPdfType.getName(index);
        List<NiceXWPFDocument> documents = new ArrayList<>();
        NiceXWPFDocument document = createWordTemplate(formSummary, index);
        documents.add(document);
        GenerateWordAndPdfUrlVO vo = CommonFormOfficeUtils.wordUpload(documents, fileName.replace("合集", "模板"));
        return vo == null ? null : vo.getWordUrl();
    }

    /**
     * 下载word模板
     *
     * @return
     */
    private static NiceXWPFDocument createWordTemplate(FireHiddenOfficeWordDTO formSummary, int index) {
        if (index == WeiQingMenPdfType.TRAFFIC_EMERGENCY_INSPECTION.getCode()) {
            // 交通应急巡查台账
            return getTRAFFIC_EMERGENCY_INSPECTION(formSummary);
        }
        if (index == WeiQingMenPdfType.THREE_IN_ONE_INSPECTION.getCode()) {
            // 三合一应急巡查台账
            return getTHREE_IN_ONE_INSPECTION(formSummary);
        }
        if (index == WeiQingMenPdfType.EMERGENCY_INSPECTION.getCode()) {
            // 应急巡查台账
            return getEMERGENCY_INSPECTION(formSummary);
        }
        if (index == WeiQingMenPdfType.SAFETY_INVESTIGATE_RENOVATE.getCode()) {
            // 安全排查整治表
            return getSAFETY_INVESTIGATE_RENOVATE(formSummary);
        }
        if (index == WeiQingMenPdfType.FIRE_SAFETY_IN_CATERING_ESTABLISHMENTS.getCode()) {
            // 餐饮经营服务场所消防安全巡查台账）
            return getFIRE_SAFETY_IN_CATERING_ESTABLISHMENTS(formSummary);
        }
        if (index == WeiQingMenPdfType.BOTTLED_GAS_USER_SAFETY_MANAGEMENT.getCode()) {
            // 瓶装燃气用户安全管理巡查台账
            return getBOTTLED_GAS_USER_SAFETY_MANAGEMENT(formSummary);
        }
        if (index == WeiQingMenPdfType.WORK_SAFETY_RECTIFICATION_NOTICE.getCode()) {
            // 重点场所隐患巡查台账
            return getWORK_SAFETY_RECTIFICATION_NOTICE(formSummary);
        }
        return null;
    }

    private static NiceXWPFDocument getSAFETY_INVESTIGATE_RENOVATE(FireHiddenOfficeWordDTO formSummary) {
        
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a2", null);
        dataMap.put("a3", null);
        dataMap.put("a4", null);
        dataMap.put("a10", null);
        dataMap.put("a11", null);
        dataMap.put("a38", null);
        //设置图片
        setDoorPicture(formSummary, dataMap);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/safetyInvestigateRenovate.docx");
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    private static NiceXWPFDocument getTRAFFIC_EMERGENCY_INSPECTION(FireHiddenOfficeWordDTO formSummary) {
  
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a1", null);
        dataMap.put("a15", null);
        dataMap.put("a3", null);
        dataMap.put("a4", null);
        dataMap.put("a33", null);
        dataMap.put("a34", null);
        dataMap.put("a10", null);
        dataMap.put("a11", null);
        dataMap.put("a12", null);
        dataMap.put("a13", null);
        dataMap.put("a14", null);
        dataMap.put("a7", null);
        dataMap.put("a38", null);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/trafficEmergencyInspection.docx");

        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    private static NiceXWPFDocument getTHREE_IN_ONE_INSPECTION(FireHiddenOfficeWordDTO formSummary) {
        
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a1", null);
        dataMap.put("a15", null);
        dataMap.put("a3", null);
        dataMap.put("a4", null);
        dataMap.put("a33", null);
        dataMap.put("a34", null);
        dataMap.put("a10", null);
        dataMap.put("a11", null);
        dataMap.put("a12", null);
        dataMap.put("a13", null);
        dataMap.put("a14", null);
        dataMap.put("a7", null);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/threeInOneInspection.docx");
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    private static NiceXWPFDocument getEMERGENCY_INSPECTION(FireHiddenOfficeWordDTO formSummary) {
        
        Map<String, Object> dataMap = Maps.newHashMap();

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/emergencyInspection.docx");
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    private static NiceXWPFDocument getBOTTLED_GAS_USER_SAFETY_MANAGEMENT(FireHiddenOfficeWordDTO formSummary) {
        Map<String, Object> dataMap = Maps.newHashMap();
        
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a2", null);
        dataMap.put("a15", null);
        dataMap.put("phone", null);
        dataMap.put("a10", null);
        dataMap.put("a45", null);
        dataMap.put("a46", null);
        dataMap.put("a47", null);
        dataMap.put("a14", null);
        dataMap.put("a38", null);
        dataMap.put("pictures", null);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/bottledGasUserSafetyManagement.docx");
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    /**
     * 应急巡查台账（物管专用）表
     *
     * @param formSummary 填表数据
     * @return 结果
     */
    private static NiceXWPFDocument getWORK_SAFETY_RECTIFICATION_NOTICE(FireHiddenOfficeWordDTO formSummary) {
        
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a1", null);
        dataMap.put("a3", null);
        dataMap.put("a4", null);
        dataMap.put("a33", null);
        dataMap.put("a34", null);
        dataMap.put("a21", null);
        dataMap.put("a22", null);
        dataMap.put("a13", null);
        dataMap.put("a14", null);
        dataMap.put("a38", null);
        //设置图片
        setDoorPicture(formSummary, dataMap);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        String templateName = "weiQingMen/template/workSafetyRectificationNotice.docx";

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap, templateName);
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    private static NiceXWPFDocument getFIRE_SAFETY_IN_CATERING_ESTABLISHMENTS(FireHiddenOfficeWordDTO formSummary) {
        
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("createDate", null);
        dataMap.put("a19", null);
        dataMap.put("a1", null);
        dataMap.put("a3", null);
        dataMap.put("a4", null);
        dataMap.put("a12", null);
        dataMap.put("a57", null);
        dataMap.put("a58", null);
        dataMap.put("a59", null);
        dataMap.put("a60", null);
        dataMap.put("a38", null);
        //设置图片
        setDoorPicture(formSummary, dataMap);

        Map<String, Object> footerMap = Maps.newHashMap();
        footerMap.put("footer", getFooter(formSummary));

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, footerMap,
                "weiQingMen/template/fireSafetyInCateringEstablishments.docx");
        NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();

        return xwpfDocument;
    }

    /**
     * 设置门头照(除危房外)
     *
     * @param formSummary
     * @return
     */
    private static boolean setDoorPicture(Sqfw_formSummary formSummary, Map<String, Object> dataMap) {
        //门头照
        String door_title = "附件：{} {} 门头照";
        door_title = StrFormatter.format(door_title, null,
                null);
        List<Map> door_pictures = new ArrayList<>();
        String a18 = formSummary.getA18();
        if (!StrUtil.isBlank(a18)) {
            String[] door_picture = a18.split(",");
            for (String url : door_picture) {
                if (!StrUtil.isBlank(url)) {
                    Map<String, Object> pictureMap = Maps.newHashMap();
                    pictureMap.put("picture", PictureUtils.scaleImage(url, 240, false));
                    door_pictures.add(pictureMap);
                }
            }
        }
        dataMap.put("door_title", door_pictures.size() == 0 ? "" : door_title);
        dataMap.put("door_pictures", door_pictures);
        return door_pictures.size() == 0 ? false : true;
    }

    /**
     * 设置整改照片(除危房外)
     *
     * @param formSummary
     * @return
     */
    private static boolean setChangePicture(Sqfw_formSummary formSummary, Map<String, Object> dataMap) {
        if (StringUtils.isBlank(formSummary.getA43())) {
            dataMap.put("before_title", "");
            dataMap.put("before_pictures", new ArrayList<>());
            dataMap.put("after_title", "");
            dataMap.put("after_pictures", new ArrayList<>());
            return false;
        }
        //因为老数据的a43不是数组，所以要在此判断
        boolean isArray = true;
        JSONArray a43 = null;
        try {
            a43 = JSON.parseArray(formSummary.getA43());
        } catch (Exception e) {
            isArray = false;
        }
        //整改前
        String before_title = "附件：{} {} 整改前照片";
        before_title = StrFormatter.format(before_title, null,
                null);
        List<Map> before_pictures = new ArrayList<>();
        String[] before_picture = isArray ? a43.getString(0).split(",") : formSummary.getA43().split(",");
        for (String url : before_picture) {
            if (!StrUtil.isBlank(url)) {
                Map<String, Object> pictureMap = Maps.newHashMap();
                pictureMap.put("picture", PictureUtils.scaleImage(url, 240, false));
                before_pictures.add(pictureMap);
            }
        }
        dataMap.put("before_title", before_pictures.size() == 0 ? "" : before_title);
        dataMap.put("before_pictures", before_pictures);
        //整改后
        String after_title = "附件：{} {} 整改后照片";
        String after_date = null;
        // a63为整改后图片更新的时间，如果不为空，则取这个时间(该字段格式：yyyy-MM-dd HH:mm:ss)
        String a63 = formSummary.getA63();
        if (!StrUtil.isBlank(a63)) {
            after_date = a63.substring(0, 10);
        }
        after_title = StrFormatter.format(after_title, null, after_date);
        List<Map> after_pictures = new ArrayList<>();
        String[] after_picture = isArray ? a43.getString(1).split(",") : formSummary.getA43().split(",");
        for (String url : after_picture) {
            if (!StrUtil.isBlank(url)) {
                Map<String, Object> pictureMap = Maps.newHashMap();
                pictureMap.put("picture", PictureUtils.scaleImage(url, 240, false));
                after_pictures.add(pictureMap);
            }
        }
        dataMap.put("after_title", after_pictures.size() == 0 ? "" : after_title);
        dataMap.put("after_pictures", after_pictures);
        return before_pictures.size() + after_pictures.size() == 0 ? false : true;
    }

    /**
     * 获取门头照(危房专用)
     *
     * @param formSummary
     * @return
     */
    private static List<Map> getDoorPicture(Sqfw_formSummary formSummary) {
        if (StringUtils.isBlank(formSummary.getA43())) {
            return new ArrayList<>();
        }
        //因为老数据的a43不是数组，所以要在此判断
        boolean isArray = true;
        JSONArray a43 = null;
        try {
            a43 = JSON.parseArray(formSummary.getA43());
        } catch (Exception e) {
            isArray = false;
        }
        List<Map> pictures = new ArrayList<>();
        String[] morning = isArray ? a43.getString(2).split(",") : formSummary.getA43().split(",");
        String[] noon = isArray ? a43.getString(3).split(",") : formSummary.getA43().split(",");
        String[] night = isArray ? a43.getString(4).split(",") : formSummary.getA43().split(",");
        for (String url : morning) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        for (String url : noon) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        for (String url : night) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        return pictures;
    }

    private static String getFooter(Sqfw_formSummary formSummary) {
        String str = "居委会";
        return UNIT_NAME.equals(formSummary.getUnitName()) ? "威清门应急服务中心" :
                formSummary.getCommunity() + str;
    }
}
